const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const ruleEngine = require('./rule-engine');

// 创建Express应用
const app = express();
const server = http.createServer(app);

// 创建Socket.IO实例
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

// 中间件
app.use(express.json());

// API路由
app.get('/api/rules', (req, res) => {
    res.json(ruleEngine.getRules());
});

app.post('/api/rules', (req, res) => {
    const rule = req.body;
    ruleEngine.addRule(rule);
    res.json({ success: true });
});

app.delete('/api/rules/:id', (req, res) => {
    const { id } = req.params;
    ruleEngine.removeRule(id);
    res.json({ success: true });
});

app.post('/api/rules/:id/activate', (req, res) => {
    const { id } = req.params;
    ruleEngine.activateRule(id);
    res.json({ success: true });
});

app.post('/api/rules/:id/deactivate', (req, res) => {
    const { id } = req.params;
    ruleEngine.deactivateRule(id);
    res.json({ success: true });
});

app.post('/api/variables', (req, res) => {
    const { variables } = req.body;
    ruleEngine.updateVariables(variables);
    res.json({ success: true });
});

app.get('/api/variables', (req, res) => {
    res.json(ruleEngine.getAllVariables());
});

// Socket.IO连接处理
io.on('connection', (socket) => {
    console.log('🔗 规则引擎客户端已连接');
    
    // 监听规则添加请求
    socket.on('add-rule', (rule) => {
        console.log('📥 收到规则添加请求:', rule);
        ruleEngine.addRule(rule);
        socket.emit('rule-added', { success: true });
    });
    
    // 监听变量更新请求
    socket.on('update-variables', (variables) => {
        console.log('🔄 收到变量更新请求:', variables);
        ruleEngine.updateVariables(variables);
        // 广播变量更新
        io.emit('variables-updated', ruleEngine.getAllVariables());
    });
    
    // 获取所有规则
    socket.on('get-rules', () => {
        const rules = ruleEngine.getRules();
        socket.emit('rules-list', rules);
    });
    
    // 获取所有变量
    socket.on('get-variables', () => {
        const variables = ruleEngine.getAllVariables();
        socket.emit('variables-list', variables);
    });
    
    socket.on('disconnect', () => {
        console.log('🔌 规则引擎客户端已断开');
    });
});

// 启动服务器
const PORT = 3004;
server.listen(PORT, () => {
    console.log(`🚀 规则引擎服务运行在端口 ${PORT}`);
    console.log(`📡 API端点: http://localhost:${PORT}/api`);
    console.log(`🔌 Socket.IO: http://localhost:${PORT}`);
});

// 示例规则
console.log('📋 添加示例规则...');
ruleEngine.addRule({
    name: '温度过高警告',
    description: '当温度传感器值超过80度时触发警告',
    condition: {
        variable: 'DB1,REAL6',
        operator: '>',
        value: 80
    },
    actions: [
        {
            type: 'notification',
            message: '温度过高警告: 温度超过80度'
        },
        {
            type: 'log',
            message: '温度过高事件记录'
        }
    ]
});

ruleEngine.addRule({
    name: '自动启动电机',
    description: '当货位1状态为就绪且温度正常时启动电机',
    condition: {
        and: [
            {
                variable: 'DB1,W0',
                operator: '===',
                value: 1
            },
            {
                variable: 'DB1,REAL6',
                operator: '<',
                value: 75
            }
        ]
    },
    actions: [
        {
            type: 'plc-write',
            variable: 'DB2,X0.0',
            value: true
        },
        {
            type: 'log',
            message: '自动启动电机'
        }
    ]
});

module.exports = { app, server };